/*
 *
   gcc gles2font.c -L. -lGLESv2 -lmingw32 -lSDL2_test -lSDL2main -lSDL2 -lSDL2_ttf -lSDL2_image && a 
   gcc gles2font.c SDL_test_common.c -lSDL2_ttf -lm -lSDL2 && ./a.out && ./a.out
   gcc gles2font.c SDL_test_common.c -L. -lGLESv2 -lmingw32 -lSDL2main -lSDL2   && a
   adb push 2.c /sdcard/ &&
   Copyright (r) 1997-2014 Sam Lantinga <slouken@libsdl.org>

   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely.
   */
#include "gles2base.h"
#include "SDL2/SDL.h"
SDL_Surface *make_txt(const char*message)
{
	const char*ttf_file = "C:/WINDOWS/Fonts/simkai.ttf";
#if defined(__ANDROID__)
	ttf_file ="/system/fonts/DroidSansFallback.ttf";	
#elif defined(linux)
	ttf_file ="/usr/share/fonts/adobe-source-han-sans-cn/SourceHanSansCN-Light.otf";	
#endif
	SDL_Color white = { 0xff, 0xff, 0xff, 0 };
	SDL_Color black = { 0x0, 0x00, 0x00, 0 };

	if ( TTF_Init() < 0 ) {
		fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
		SDL_Quit();
		return NULL;
	}
	TTF_Font * font = TTF_OpenFont(ttf_file, 26);
	TTF_SetFontStyle(font, TTF_STYLE_NORMAL);
	SDL_Surface* text;
	text = TTF_RenderUTF8_Shaded(font, message, black,white);
	//text = TTF_RenderUNICODE_Shaded(font, message, black,white);
	//text =  TTF_RenderText_Shaded(font, message, black,white);
	//text =  TTF_RenderGlyph_Shaded(font, *message, black,white);
	int ww,hh; TTF_SizeText(font, message, &ww, &hh); SDL_Log("font height:%d,%dx%d\n",TTF_FontHeight(font),ww,hh);
	TTF_CloseFont(font);
	return text;
}
GLuint _SDL_GL_LoadTexture(SDL_Surface * surface, GLfloat * texcoord)
{
	GLuint texture;
	int w, h;
	SDL_Surface *image;
	SDL_Rect area;
	SDL_BlendMode saved_mode;
	/* Use the surface width and height expanded to powers of 2 */
	w = surface->w;
	h = surface->h;
	if(texcoord){
		texcoord[0] = 0.0f;         /* Min X */
		texcoord[1] = 0.0f;         /* Min Y */
		texcoord[2] = (GLfloat) surface->w / w;     /* Max X */
		texcoord[3] = (GLfloat) surface->h / h;     /* Max Y */
	}

	image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN     /* OpenGL RGBA masks */
			0x000000FF,
			0x0000FF00,
			0x00FF0000,
			0xFF000000
#else
			0xFF000000,
			0x00FF0000,
			0x0000FF00,
			0x000000FF
#endif
			);
	if (image == NULL) {
		return 0;
	}
	/* Save the alpha blending attributes */
	SDL_GetSurfaceBlendMode(surface, &saved_mode);
	SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);

	/* Copy the surface into the GL texture image */
	area.x = 0;
	area.y = 0;
	area.w = surface->w;
	area.h = surface->h;
	SDL_Rect area2;
	area2.x = 0;
	area2.y = 0;
	area2.w = image->w;
	area2.h = image->h;
	SDL_BlitSurface(surface, NULL, image, NULL);
	/* Restore the alpha blending attributes */
	SDL_SetSurfaceBlendMode(surface, saved_mode);
	/* Create an OpenGL texture for the image */
	ctx.glGenTextures(1, &texture);
	ctx.glBindTexture(GL_TEXTURE_2D, texture);
	ctx.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	ctx.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	ctx.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);
	SDL_FreeSurface(image);     /* No longer needed */
	return texture;
}

int Init ( UserData*userData)
{
	GLbyte vShaderStr[] =  
		"attribute vec4 a_position;   \n"
		"attribute vec2 a_texCoord;   \n"
		"varying vec2 v_texCoord;     \n"
		"void main()                  \n"
		"{                            \n"
		"   gl_Position = a_position; \n"
		"   v_texCoord = a_texCoord;  \n"
		"}                            \n";

	GLbyte fShaderStr[] =  
		"precision mediump float;                            \n"
		"varying vec2 v_texCoord;                            \n"
		"uniform sampler2D s_texture;                        \n"
		"void main()                                         \n"
		"{                                                   \n"
		"  gl_FragColor = texture2D( s_texture, v_texCoord );\n"
		"}                                                   \n";

	// Load the shaders and get a linked program object
	userData->programObject = esLoadProgram ( vShaderStr, fShaderStr );

	// Get the attribute locations
	userData->positionLoc = ctx.glGetAttribLocation ( userData->programObject, "a_position" );
	userData->texCoordLoc = ctx.glGetAttribLocation ( userData->programObject, "a_texCoord" );

	// Get the sampler location
	userData->samplerLoc = ctx.glGetUniformLocation ( userData->programObject, "s_texture" );

	// Load the texture
	SDL_Surface *surface = make_txt("【表】");//IMG_Load("0.jpg");
	if ( ! surface ) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load icon.bmp: %s\n", SDL_GetError());
		userData->textureId = CreateSimpleTexture2D ();
	}else{
		GLfloat texcoords[4];
		userData->textureId = _SDL_GL_LoadTexture(surface, texcoords);
		SDL_FreeSurface(surface);
	}

	ctx.glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );
	return 1;
}

void Draw( UserData*userData)
{
	GLfloat vVertices[] = {
		-0.5f,  0.5f, 0.0f,  // Position 0
		0.0f,  0.0f,        // TexCoord 0 
		-0.5f, -0.5f, 0.0f,  // Position 1
		0.0f,  1.0f,        // TexCoord 1
		0.5f, -0.5f, 0.0f,  // Position 2
		1.0f,  1.0f,        // TexCoord 2
		0.5f,  0.5f, 0.0f,  // Position 3
		1.0f,  0.0f         // TexCoord 3
	};
	GLushort indices[] = { 0, 1, 2, 0, 2, 3 };
	// Set the viewport
	ctx.glViewport ( 0, 0, state->window_w, state->window_h);

	// Clear the color buffer
	ctx.glClear ( GL_COLOR_BUFFER_BIT );

	// Use the program object
	ctx.glUseProgram ( userData->programObject );

	// Load the vertex position
	ctx.glVertexAttribPointer ( userData->positionLoc, 3, GL_FLOAT, 
			GL_FALSE, 5 * sizeof(GLfloat), vVertices );
	// Load the texture coordinate
	ctx.glVertexAttribPointer ( userData->texCoordLoc, 2, GL_FLOAT,
			GL_FALSE, 5 * sizeof(GLfloat), &vVertices[3] );

	ctx.glEnableVertexAttribArray ( userData->positionLoc );
	ctx.glEnableVertexAttribArray ( userData->texCoordLoc );

	// Bind the texture
	ctx.glActiveTexture ( GL_TEXTURE0 );
	ctx.glBindTexture ( GL_TEXTURE_2D, userData->textureId );

	// Set the sampler texture unit to 0
	ctx.glUniform1i ( userData->samplerLoc, 0 );
	ctx.glDrawElements ( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices );
	/*eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );*/
}

